#include "sw/redis++/redis.h"
#include <gflags/gflags.h>
#include <iostream>
#include <thread>

DEFINE_string(ip,"127.0.0.1","这是服务器的ip地址,格式:127.0.0.1");
DEFINE_int32(port,6379,"这是服务器的监听端口，格式6379");
DEFINE_int32(db,0,"这是服务器的数据库编号，默认0");
DEFINE_bool(keep_alive,true,"是否保持长连接,格式:true/false");
void print(sw::redis::Redis &client)
{
 auto usr1 = client.get("会话ID1");
    if(usr1)std::cout<<*usr1<<std::endl;
    else std::cout<<"会话ID1不存在"<<std::endl;
    auto usr2 = client.get("会话ID2");
    if(usr2)std::cout<<*usr2<<std::endl;
    else std::cout<<"会话ID2不存在"<<std::endl;
    auto usr3 = client.get("会话ID3");
    if(usr3)std::cout<<*usr3<<std::endl;
    else std::cout<<"会话ID3不存在"<<std::endl;
    auto usr4 = client.get("会话ID4");
    if(usr4)std::cout<<*usr4<<std::endl;
    else std::cout<<"会话ID4不存在"<<std::endl;
    auto usr5 = client.get("会话ID5");
    if(usr5)std::cout<<*usr5<<std::endl;
    else std::cout<<"会话ID5不存在"<<std::endl;
}
void add_string(sw::redis::Redis &client)
{
    //2.添加字符串
    client.set("会话ID1","用户ID1");
    client.set("会话ID2","用户ID2");
    client.set("会话ID3","用户ID3");
    client.set("会话ID4","用户ID4");
    client.set("会话ID5","用户ID5");
    client .del("会话ID3");

    client.set("会话ID5","用户ID5555");
   
    print(client);


}
void expired_test(sw::redis::Redis &client)
{
    client.set("会话ID1","用户ID1111",std::chrono::milliseconds(1000));
    print(client);
    std::this_thread::sleep_for(std::chrono::seconds(2));
    print(client);
}
void list_test(sw::redis::Redis &client)
{
    //3.添加列表
    client.rpush("群聊1","用户ID1");
    client.rpush("群聊1","用户ID2");
    client.rpush("群聊1","用户ID3");
    client.rpush("群聊1","用户ID4");
    client.rpush("群聊1","用户ID5");

    //4.获取列表
    std::vector<std::string> list;
    client.lrange("群聊1",0,-1,std::back_inserter(list));

    for(auto &item:list)
    {
        std::cout<<item<<std::endl;
    }

}
int main(int argc, char *argv[])
{
    google::ParseCommandLineFlags(&argc,&argv,true);
    //1.连接redis
    sw::redis::ConnectionOptions opts;
    opts.host = FLAGS_ip;
    opts.port = FLAGS_port;
    opts.db = FLAGS_db;
    opts.keep_alive = FLAGS_keep_alive;
    sw::redis::Redis client(opts);
    add_string(client);
    expired_test(client);
    list_test(client);
}